<template>
  <div class="analysis-report">
    <!-- 分析概览 -->
    <div class="analysis-overview">
      <div class="overview-cards">
        <div class="overview-card sales-trend">
          <div class="card-header">
            <h3>销售趋势</h3>
            <span class="trend-indicator" :class="salesTrend.direction">
              {{ salesTrend.direction === 'up' ? '↗' : salesTrend.direction === 'down' ? '↘' : '→' }}
              {{ salesTrend.percentage }}%
            </span>
          </div>
          <div class="card-content">
            <div class="metric-large">¥{{ formatNumber(salesTrend.current) }}</div>
            <div class="metric-subtitle">本期销售额</div>
          </div>
        </div>

        <div class="overview-card order-analysis">
          <div class="card-header">
            <h3>订单分析</h3>
            <span class="metric-small">{{ orderAnalysis.avgOrderValue }}元/单</span>
          </div>
          <div class="card-content">
            <div class="metric-large">{{ orderAnalysis.totalOrders }}</div>
            <div class="metric-subtitle">总订单数</div>
          </div>
        </div>

        <div class="overview-card customer-analysis">
          <div class="card-header">
            <h3>客户分析</h3>
            <span class="metric-small">{{ customerAnalysis.repeatRate }}% 复购率</span>
          </div>
          <div class="card-content">
            <div class="metric-large">{{ customerAnalysis.totalCustomers }}</div>
            <div class="metric-subtitle">活跃客户</div>
          </div>
        </div>

        <div class="overview-card profit-analysis">
          <div class="card-header">
            <h3>利润分析</h3>
            <span class="metric-small">{{ profitAnalysis.margin }}% 毛利率</span>
          </div>
          <div class="card-content">
            <div class="metric-large">¥{{ formatNumber(profitAnalysis.totalProfit) }}</div>
            <div class="metric-subtitle">总毛利</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 图表分析区域 -->
    <div class="charts-section">
      <div class="chart-row">
        <!-- 销售趋势图表 -->
        <div class="chart-container">
          <div class="chart-header">
            <h4>销售趋势分析</h4>
            <div class="chart-controls">
              <select v-model="trendPeriod" @change="updateTrendChart">
                <option value="7">近7天</option>
                <option value="30">近30天</option>
                <option value="90">近90天</option>
              </select>
            </div>
          </div>
          <div class="chart-content">
            <canvas ref="trendChart" width="400" height="200"></canvas>
          </div>
        </div>

        <!-- 商品类别分析 -->
        <div class="chart-container">
          <div class="chart-header">
            <h4>商品类别分析</h4>
          </div>
          <div class="chart-content">
            <canvas ref="categoryChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>

      <div class="chart-row">
        <!-- 时段分析 -->
        <div class="chart-container">
          <div class="chart-header">
            <h4>销售时段分析</h4>
          </div>
          <div class="chart-content">
            <canvas ref="hourlyChart" width="400" height="200"></canvas>
          </div>
        </div>

        <!-- 支付方式分析 -->
        <div class="chart-container">
          <div class="chart-header">
            <h4>支付方式分析</h4>
          </div>
          <div class="chart-content">
            <canvas ref="paymentChart" width="400" height="200"></canvas>
          </div>
        </div>
      </div>

      <!-- 热力图分析 -->
      <div class="chart-row">
        <div class="chart-container full-width">
          <div class="chart-header">
            <h4>销售热力图分析</h4>
            <div class="chart-controls">
              <select v-model="heatmapType" @change="updateHeatmap">
                <option value="hourly">时段热力图</option>
                <option value="weekly">周期热力图</option>
                <option value="product">商品热力图</option>
              </select>
            </div>
          </div>
          <div class="chart-content">
            <canvas ref="heatmapChart" width="800" height="300"></canvas>
          </div>
        </div>
      </div>
    </div>

    <!-- 详细分析表格 -->
    <div class="analysis-tables">
      <div class="table-section">
        <div class="table-header">
          <h4>商品销售排行</h4>
          <button @click="exportProductRanking" class="btn-export">导出</button>
        </div>
        <div class="table-wrapper">
          <table class="analysis-table">
            <thead>
              <tr>
                <th>排名</th>
                <th>商品名称</th>
                <th>商品代码</th>
                <th>销售数量</th>
                <th>销售金额</th>
                <th>占比</th>
                <th>增长率</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in productRanking" :key="index">
                <td class="text-center">{{ index + 1 }}</td>
                <td>{{ item.name }}</td>
                <td>{{ item.code }}</td>
                <td class="text-right">{{ item.quantity }}</td>
                <td class="text-right">¥{{ item.sales.toFixed(2) }}</td>
                <td class="text-right">{{ item.percentage }}%</td>
                <td class="text-right" :class="{ 'positive': item.growth > 0, 'negative': item.growth < 0 }">
                  {{ item.growth > 0 ? '+' : '' }}{{ item.growth }}%
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <div class="table-section">
        <div class="table-header">
          <h4>时段销售分析</h4>
          <button @click="exportHourlyAnalysis" class="btn-export">导出</button>
        </div>
        <div class="table-wrapper">
          <table class="analysis-table">
            <thead>
              <tr>
                <th>时段</th>
                <th>订单数</th>
                <th>销售额</th>
                <th>平均客单价</th>
                <th>占比</th>
                <th>同比增长</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in hourlyAnalysis" :key="index">
                <td>{{ item.hour }}:00-{{ item.hour + 1 }}:00</td>
                <td class="text-right">{{ item.orders }}</td>
                <td class="text-right">¥{{ item.sales.toFixed(2) }}</td>
                <td class="text-right">¥{{ item.avgOrder.toFixed(2) }}</td>
                <td class="text-right">{{ item.percentage }}%</td>
                <td class="text-right" :class="{ 'positive': item.growth > 0, 'negative': item.growth < 0 }">
                  {{ item.growth > 0 ? '+' : '' }}{{ item.growth }}%
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue'
import { ChartUtils, ExportUtils } from './ChartUtils.js'

const props = defineProps({
  data: {
    type: Array,
    default: () => []
  },
  filters: {
    type: Object,
    default: () => ({})
  }
})

// 图表引用
const trendChart = ref(null)
const categoryChart = ref(null)
const hourlyChart = ref(null)
const paymentChart = ref(null)
const heatmapChart = ref(null)

// 趋势分析周期
const trendPeriod = ref('30')

// 热力图类型
const heatmapType = ref('hourly')

// 销售趋势分析
const salesTrend = computed(() => {
  // 模拟数据，实际应该从props.data计算
  return {
    current: 156800,
    previous: 142300,
    direction: 'up',
    percentage: 10.2
  }
})

// 订单分析
const orderAnalysis = computed(() => {
  return {
    totalOrders: 1580,
    avgOrderValue: 99.24,
    completionRate: 98.5
  }
})

// 客户分析
const customerAnalysis = computed(() => {
  return {
    totalCustomers: 892,
    newCustomers: 156,
    repeatRate: 67.8
  }
})

// 利润分析
const profitAnalysis = computed(() => {
  return {
    totalProfit: 47040,
    margin: 30.0,
    growth: 8.5
  }
})

// 商品销售排行
const productRanking = computed(() => {
  return [
    { name: '可口可乐', code: '001001', quantity: 256, sales: 896.00, percentage: 12.5, growth: 8.2 },
    { name: '薯片', code: '002001', quantity: 189, sales: 1681.00, percentage: 23.4, growth: 15.6 },
    { name: '矿泉水', code: '003001', quantity: 445, sales: 890.00, percentage: 12.4, growth: -2.3 },
    { name: '面包', code: '004001', quantity: 167, sales: 1169.00, percentage: 16.3, growth: 5.7 },
    { name: '牛奶', code: '005001', quantity: 234, sales: 1404.00, percentage: 19.6, growth: 12.1 }
  ]
})

// 时段分析
const hourlyAnalysis = computed(() => {
  return [
    { hour: 9, orders: 45, sales: 2340.00, avgOrder: 52.00, percentage: 8.2, growth: 5.3 },
    { hour: 10, orders: 78, sales: 4680.00, avgOrder: 60.00, percentage: 16.4, growth: 8.7 },
    { hour: 11, orders: 95, sales: 5700.00, avgOrder: 60.00, percentage: 20.0, growth: 12.1 },
    { hour: 12, orders: 120, sales: 7200.00, avgOrder: 60.00, percentage: 25.2, growth: 15.6 },
    { hour: 13, orders: 89, sales: 5340.00, avgOrder: 60.00, percentage: 18.7, growth: 3.4 },
    { hour: 14, orders: 56, sales: 3360.00, avgOrder: 60.00, percentage: 11.8, growth: -1.2 }
  ]
})

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString()
}

// 绘制趋势图表
const drawTrendChart = () => {
  const canvas = trendChart.value
  if (!canvas) return
  
  const chartData = {
    labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    datasets: [
      {
        label: '销售额',
        data: [1200, 1350, 1100, 1450, 1680, 1520, 1750]
      }
    ]
  }
  
  ChartUtils.drawLineChart(canvas, chartData, {
    colors: ['#1890ff'],
    showGrid: true,
    showLabels: true
  })
}

// 绘制类别饼图
const drawCategoryChart = () => {
  const canvas = categoryChart.value
  if (!canvas) return
  
  const pieData = [
    { label: '饮料', value: 35 },
    { label: '零食', value: 28 },
    { label: '日用品', value: 22 },
    { label: '其他', value: 15 }
  ]
  
  ChartUtils.drawPieChart(canvas, pieData, {
    colors: ['#1890ff', '#52c41a', '#faad14', '#f5222d'],
    showLabels: true,
    showPercentages: true
  })
}

// 更新趋势图表
const updateTrendChart = () => {
  nextTick(() => {
    drawTrendChart()
  })
}

// 导出商品排行
const exportProductRanking = () => {
  const exportData = productRanking.value.map((item, index) => ({
    排名: index + 1,
    商品名称: item.name,
    商品代码: item.code,
    销售数量: item.quantity,
    销售金额: item.sales.toFixed(2),
    占比: item.percentage + '%',
    增长率: item.growth + '%'
  }))
  
  ExportUtils.exportToCSV(exportData, '商品销售排行.csv')
}

// 导出时段分析
const exportHourlyAnalysis = () => {
  const exportData = hourlyAnalysis.value.map((item) => ({
    时段: `${item.hour}:00-${item.hour + 1}:00`,
    订单数: item.orders,
    销售额: item.sales.toFixed(2),
    平均客单价: item.avgOrder.toFixed(2),
    占比: item.percentage + '%',
    同比增长: item.growth + '%'
  }))
  
  ExportUtils.exportToCSV(exportData, '时段销售分析.csv')
}

// 绘制时段柱状图
const drawHourlyChart = () => {
  const canvas = hourlyChart.value
  if (!canvas) return
  
  const barData = hourlyAnalysis.value.map(item => ({
    label: `${item.hour}:00`,
    value: item.orders
  }))
  
  ChartUtils.drawBarChart(canvas, barData, {
    colors: ['#52c41a'],
    showGrid: true,
    showLabels: true
  })
}

// 绘制支付方式饼图
const drawPaymentChart = () => {
  const canvas = paymentChart.value
  if (!canvas) return
  
  const paymentData = [
    { label: '现金', value: 35 },
    { label: '微信支付', value: 40 },
    { label: '支付宝', value: 20 },
    { label: '刷卡', value: 5 }
  ]
  
  ChartUtils.drawPieChart(canvas, paymentData, {
    colors: ['#faad14', '#52c41a', '#1890ff', '#f5222d'],
    showLabels: true,
    showPercentages: true
  })
}

// 绘制热力图
const drawHeatmap = () => {
  const canvas = heatmapChart.value
  if (!canvas) return
  
  let heatmapData
  
  if (heatmapType.value === 'hourly') {
    // 时段热力图：周几 x 小时
    heatmapData = {
      xLabels: ['9:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00'],
      yLabels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      values: [
        [45, 78, 95, 120, 89, 56, 67, 89, 112, 98],
        [52, 85, 102, 135, 95, 62, 74, 95, 125, 108],
        [48, 82, 98, 128, 92, 58, 70, 92, 118, 102],
        [55, 88, 105, 140, 98, 65, 77, 98, 128, 115],
        [60, 95, 115, 150, 110, 75, 85, 110, 140, 125],
        [85, 125, 145, 180, 135, 95, 110, 135, 165, 150],
        [80, 120, 140, 175, 130, 90, 105, 130, 160, 145]
      ]
    }
  } else if (heatmapType.value === 'weekly') {
    // 周期热力图：月份 x 周
    heatmapData = {
      xLabels: ['第1周', '第2周', '第3周', '第4周'],
      yLabels: ['1月', '2月', '3月', '4月', '5月', '6月'],
      values: [
        [1200, 1350, 1100, 1450],
        [1300, 1420, 1180, 1520],
        [1150, 1280, 1050, 1380],
        [1400, 1580, 1320, 1680],
        [1250, 1400, 1150, 1500],
        [1350, 1520, 1280, 1620]
      ]
    }
  } else {
    // 商品热力图：商品类别 x 时段
    heatmapData = {
      xLabels: ['9-11', '11-13', '13-15', '15-17', '17-19'],
      yLabels: ['饮料', '零食', '日用品', '烟酒', '其他'],
      values: [
        [45, 85, 65, 95, 125],
        [35, 75, 55, 85, 115],
        [25, 55, 45, 65, 85],
        [15, 35, 25, 45, 65],
        [20, 40, 30, 50, 70]
      ]
    }
  }
  
  ChartUtils.drawHeatmap(canvas, heatmapData, {
    colorScale: ['#f0f9ff', '#0ea5e9', '#0369a1'],
    showLabels: true
  })
}

// 更新热力图
const updateHeatmap = () => {
  nextTick(() => {
    drawHeatmap()
  })
}

// 初始化
onMounted(() => {
  nextTick(() => {
    drawTrendChart()
    drawCategoryChart()
    drawHourlyChart()
    drawPaymentChart()
    drawHeatmap()
  })
})
</script>

<style scoped>
.analysis-report {
  padding: 0;
}

.analysis-overview {
  margin-bottom: 30px;
}

.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.overview-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-left: 4px solid #1890ff;
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.15);
}

.overview-card.sales-trend {
  border-left-color: #1890ff;
}

.overview-card.order-analysis {
  border-left-color: #52c41a;
}

.overview-card.customer-analysis {
  border-left-color: #faad14;
}

.overview-card.profit-analysis {
  border-left-color: #f5222d;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.card-header h3 {
  margin: 0;
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.trend-indicator {
  font-size: 12px;
  font-weight: bold;
  padding: 4px 8px;
  border-radius: 4px;
}

.trend-indicator.up {
  color: #52c41a;
  background: #f6ffed;
}

.trend-indicator.down {
  color: #f5222d;
  background: #fff2f0;
}

.metric-small {
  font-size: 12px;
  color: #999;
}

.card-content {
  text-align: left;
}

.metric-large {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.metric-subtitle {
  font-size: 12px;
  color: #999;
}

.charts-section {
  margin-bottom: 30px;
}

.chart-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-bottom: 20px;
}

.chart-row .full-width {
  grid-column: 1 / -1;
}

.chart-container {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.chart-controls select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  font-size: 12px;
}

.chart-content {
  position: relative;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.chart-content canvas {
  max-width: 100%;
  max-height: 100%;
}

.analysis-tables {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.table-header h4 {
  margin: 0;
  font-size: 14px;
  color: #333;
}

.btn-export {
  padding: 6px 12px;
  background: #28a745;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.3s ease;
}

.btn-export:hover {
  background: #218838;
}

.table-wrapper {
  overflow-x: auto;
  max-height: 300px;
  overflow-y: auto;
}

.analysis-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 12px;
}

.analysis-table th {
  background: #f8f9fa;
  padding: 10px 8px;
  text-align: left;
  font-weight: 600;
  color: #495057;
  border-bottom: 1px solid #dee2e6;
  position: sticky;
  top: 0;
  z-index: 10;
}

.analysis-table td {
  padding: 8px;
  border-bottom: 1px solid #e9ecef;
}

.analysis-table tbody tr:hover {
  background: #f8f9fa;
}

.text-center {
  text-align: center;
}

.text-right {
  text-align: right;
}

.positive {
  color: #52c41a;
}

.negative {
  color: #f5222d;
}

@media (max-width: 768px) {
  .chart-row,
  .analysis-tables {
    grid-template-columns: 1fr;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
}
</style>